package com.ybfenpan.controller.core;


import com.ybfenpan.model.Member;
import com.ybfenpan.model.core.BaseBean;
import com.ybfenpan.utils.ContextUtil;
import com.ybfenpan.utils.StringUtil;
import com.ybfenpan.utils.SysConst;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class BaseController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected HashMap<String, Object> getParameterMap(HttpServletRequest request) {
		// 返回值Map
		HashMap returnMap = new HashMap();
	    // 参数Map
	    Map properties = request.getParameterMap();
	    Iterator entries = properties.entrySet().iterator();
	    while (entries.hasNext()) {
	    	Map.Entry entry = (Map.Entry) entries.next();
	        String name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	        	returnMap.put(name, "");
	        	continue;
	        }
	        if(valueObj instanceof String[]){
	        	 String[] values = (String[])valueObj;
	        	 if(1 == values.length){
	        		 valueObj = values[0];
	        	 }
	        }
	        returnMap.put(name, valueObj);
	    }
	    // 通过AjaxFormToServer提交过来的参数
	    String paramStr = MapUtils.getString(returnMap, "param");
		Map<String, Object> paraMap = JSONObject.parseObject(paramStr, Map.class);
		if(null != paraMap) returnMap.putAll(paraMap);
	    // 用户
	    Member user = ContextUtil.getMember();
		if(null != user) {
//			returnMap.put("CUR_USERCODE", user.getUserCode());
//			returnMap.put("CUR_USERNAME", user.getUserName());
//			returnMap.put("CUR_DEPTCODE", user.getDeptCode());
//			returnMap.put("CUR_DEPTNAME", user.getDeptName());
		}
	    return returnMap;
	}

	protected void renderSuccess(HttpServletResponse response, boolean flag, Object data) {
		PrintWriter writer = null;
		try {
			response.setHeader("Charset", "UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/Json;charset=utf-8");
			Map<String, Object> map = new HashMap<String, Object>();
			if(data instanceof Map){
				 
				map.putAll((Map) data);
			}
			else if(data instanceof Collection){
				 
				map.put("rows", data);
			}
			else if(data instanceof BaseBean){
				 
				map.put(data.getClass().getSimpleName(), data);
			}
			else{
				 
				map.put("message", data);
			}
			map.put("success", flag);
			String jsonStr = JSONObject.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
			writer = response.getWriter();
			writer.write(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null)
				writer.close();
		}
	}

	public void setMessage(Object obj, String msg){
		if(obj instanceof HttpServletRequest){
			HttpServletRequest request = (HttpServletRequest)obj;
			Object retObj = request.getAttribute("retMsg");
			if (null != retObj) {
				msg = retObj.toString()+"<br>"+msg;
			}
			request.setAttribute("retMsg", msg);
			request.setAttribute(SysConst.msgName, msg);
		}
		else if(obj instanceof HttpSession){
			((HttpSession)obj).setAttribute(SysConst.msgName,msg);
		}
		else if(obj instanceof ModelMap){
			((ModelMap)obj).addAttribute(SysConst.msgName, msg);
		}
		else if(obj instanceof RedirectAttributes){
			((RedirectAttributes)obj).addAttribute(SysConst.msgName,msg);
		}
	}

	/**
	 * 返回到view页面路径，通用方法，请勿修改
	 * @param request
	 * @return
	 */
	protected String forwardUrl(HttpServletRequest request) {
		String forwardPath = "", forwardName = "";
		String webApp = request.getContextPath();
		String reqUrl = request.getRequestURI().replace(".shtml", "");
		reqUrl = reqUrl.substring(reqUrl.lastIndexOf(webApp)+webApp.length());
		String[] urlArr = StringUtil.strToArray(reqUrl, "/");
		for(int i=0; i<urlArr.length; i++){
			String u = urlArr[i];
			if(StringUtils.isBlank(u))continue;
			forwardName += (i==0?u:StringUtil.toUpperCaseFirstOne(u));
			if(i != urlArr.length-1) forwardPath+=(u+"/");
		}
		//来源是否手机app
		String fm = request.getParameter("fm");//"App";//移动端（正式环境此行注释）
		fm = StringUtils.isNotBlank(fm)?fm:"";
		String forwardUrl = forwardPath + forwardName + fm;
		System.out.println("服务器响应页面: "+forwardUrl+".jsp");
		return forwardUrl;
	}
	
}
